#!/usr/bin/env bash

set -e

PTF_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
P4SRC_DIR=${PTF_DIR}/../p4src
P4C_OUT=${P4SRC_DIR}/build
DOCKER_IMG=onosproject/fabric-p4test

runName=ptf-${RANDOM}

function stop() {
        echo "Stopping container ${runName}..."
        docker stop -t0 "${runName}" > /dev/null
}
trap stop INT

# Start container. Entrypoint starts stratum_bmv2. We put that in the background
# and execute the PTF scripts separately.
echo "*** Starting BMv2 simple_switch in Docker (${runName})..."
docker run --name "${runName}" -d --privileged --rm \
    -v "${PTF_DIR}":/ptf -w /ptf \
    -v "${P4C_OUT}":/p4c-out \
    "${DOCKER_IMG}" \
    ./lib/start_bmv2.sh > /dev/null

sleep 2

set +e

printf "*** Starting tests...\n"
docker exec "${runName}" ./lib/runner.py \
    --bmv2-json /p4c-out/bmv2.json \
    --p4info /p4c-out/p4info.txt \
    --grpc-addr localhost:28000 \
    --device-id 1 \
    --ptf-dir ./tests \
    --cpu-port 255 \
    --port-map /ptf/lib/port_map.json "${@}"

stop
